package com.caocaog.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.entity.GoodsSort;
import com.caocaog.market.entity.ShopBasic;
import com.caocaog.market.service.IGoodsSortService;
import com.caocaog.market.service.IShopBasicService;
import com.caocaog.market.vo.LabelAndValueVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 商品分类表
 * @Author: guofeiyan
 * @Date: 2021-11-11
 * @Version: V1.0
 */
@Deprecated //  TODO 04-24号没问题后删除 接口已全部迁移至GoodsCategoriesController
@Api(tags = "商品分类表")
@RestController
@RequestMapping("/goods/goodsCategories")
@Slf4j
public class GoodsSortController extends JeecgController<GoodsSort, IGoodsSortService> {
    @Autowired
    private IGoodsSortService goodsSortService;
    @Autowired
    private IShopBasicService shopBasicService;
    @Autowired
    private CommonAPI commonAPI;


    @AutoLog(value = "商品分类表-根据店铺id获取")
    @ApiOperation(value = "商品分类表-根据店铺id获取")
    @GetMapping(value = "/getList")
    public Result<List<GoodsSort>> getList(@RequestParam("shopId")String shopId) {
        return Result.OK(goodsSortService.getShopSortList(shopId));
    }

    /**
     * 分页列表查询
     *
     * @param goodsSort
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商品分类表-分页列表查询")
    @ApiOperation(value = "商品分类表-分页列表查询", notes = "商品分类表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GoodsSort goodsSort,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if (oConvertUtils.isEmpty(goodsSort.getShopId())) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isNotEmpty(loginUser.getUserType()) && 1 != loginUser.getUserType()) {
                LambdaQueryWrapper<ShopBasic> shopQuery = new LambdaQueryWrapper<>();
                if (2 == loginUser.getUserType()) {

                    //分站
                    String siteId = loginUser.getSiteId();
                    //获取商户ids
                    List<String> merchantIds = commonAPI.findMerchantForSite(siteId);
                    //获取门店
                    if (oConvertUtils.listIsNotEmpty(merchantIds)) {

                        shopQuery.in(ShopBasic::getMerchantId, merchantIds);
                        List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                        if (oConvertUtils.listIsNotEmpty(shopIds)) {
                            goodsSort.setShopId(StringUtils.join(shopIds, StringPool.COMMA));
                        } else {
                            return Result.error("暂无数据");
                        }

                    }

                } else if (3 == loginUser.getUserType()) {
                    //商户
                    String merchantId = loginUser.getMerchantId();
                    //获取门店
                    // 首先获取选择的门店
                    if (oConvertUtils.isNotEmpty(loginUser.getCurrentSelectedShopId())) {
                        goodsSort.setShopId(loginUser.getCurrentSelectedShopId());
                    } else {
                        shopQuery.eq(ShopBasic::getMerchantId, merchantId);
                        List<String> shopIds = shopBasicService.list(shopQuery).stream().map(ShopBasic::getId).collect(Collectors.toList());
                        if (oConvertUtils.listIsNotEmpty(shopIds)) {
                            goodsSort.setShopId(StringUtils.join(shopIds, StringPool.COMMA));
                        } else {
                            //当前无门店
                            return Result.error("您还没有自己的门店,请先添加自己的门店哟~");
                        }
                    }


                }
            }
        }

        Page<GoodsSort> page = new Page<>(pageNo, pageSize);
        IPage<GoodsSort> pageList = goodsSortService.queryGoodsSortPage(page, goodsSort);
        return Result.OK(pageList);
    }

    /**
     * 通过shopid查询分类
     *
     * @return
     */
    @AutoLog(value = "通过shopId查询商品分类")
    @ApiOperation(value = "通过shopId查询商品分类", notes = "通过shopId查询商品分类")
    @GetMapping(value = "/querySortsByShopId")
    public Result<?> querySortsByShopId() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId()))
            throw new JeecgBootException("用户暂未绑定门店, realName-> " + loginUser.getRealname());

        LambdaQueryWrapper<GoodsSort> goodsSortQuery = new LambdaQueryWrapper<GoodsSort>();
        goodsSortQuery.eq(GoodsSort::getShopId, loginUser.getCurrentSelectedShopId());
        List<GoodsSort> goodsSortList = goodsSortService.list(goodsSortQuery);
        List<LabelAndValueVo> vos = new ArrayList<>();
        for (GoodsSort sort : goodsSortList) {
            LabelAndValueVo vo = new LabelAndValueVo();
            vo.setLabel(sort.getName());
            vo.setValue(sort.getId());
            vos.add(vo);
        }
        return Result.OK(vos);
    }

    /**
     * 添加
     *
     * @param goodsSort
     * @return
     */
    @AutoLog(value = "商品分类表-添加")
    @ApiOperation(value = "商品分类表-添加", notes = "商品分类表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GoodsSort goodsSort) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId()))
            throw new JeecgBootException("用户暂未绑定门店, realName-> " + loginUser.getRealname());
        goodsSort.setShopId(loginUser.getCurrentSelectedShopId());
        if (oConvertUtils.isNotEmpty(goodsSort.getSortName())) {
            goodsSort.setShopId(goodsSort.getShopId());
            goodsSort.setSort(0);
            goodsSort.setName(goodsSort.getSortName());
            goodsSort.setIsShow("1");
            goodsSort.setDelFlag(0);
        }
        if (oConvertUtils.isEmpty(goodsSort.getName()) ) {
            return Result.error("参数错误~");
        }
        //check 该门店内的分类是否重复
        GoodsSort shopCategoryCheck = goodsSortService.getOne(new QueryWrapper<GoodsSort>().eq("shop_id", goodsSort.getShopId())
                .eq("name", goodsSort.getName()));
        if (oConvertUtils.isNotEmpty(shopCategoryCheck)) {
            return Result.error("该门店已有该分类[" + goodsSort.getName() + "],请勿重复添加哟~");
        }

        goodsSortService.save(goodsSort);
        return Result.OK("添加成功！", true);
    }

    /**
     * 编辑
     *
     * @param goodsSort
     * @return
     */
    @AutoLog(value = "商品分类表-编辑")
    @ApiOperation(value = "商品分类表-编辑", notes = "商品分类表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody GoodsSort goodsSort) {
        if (oConvertUtils.isEmpty(goodsSort.getId()) || oConvertUtils.isEmpty(goodsSort.getName())
                || oConvertUtils.isEmpty(goodsSort.getShopId())) {
            return Result.error("参数错误~");
        }
        //check 该门店内的分类是否重复
        GoodsSort shopCategoryCheck = goodsSortService.getOne(
                new QueryWrapper<GoodsSort>().eq("shop_id", goodsSort.getShopId())
                        .eq("name", goodsSort.getName()));
        if (oConvertUtils.isNotEmpty(shopCategoryCheck) && !goodsSort.getId().equals(shopCategoryCheck.getId())) {
            return Result.error("该门店已有该分类[" + goodsSort.getName() + "],请勿重复添加哟~");
        }
        goodsSortService.updateById(goodsSort);
        return Result.OK("编辑成功!", true);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品分类表-通过id删除")
    @ApiOperation(value = "商品分类表-通过id删除", notes = "商品分类表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        goodsSortService.removeById(id);
        return Result.OK("删除成功!", true);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品分类表-批量删除")
    @ApiOperation(value = "商品分类表-批量删除", notes = "商品分类表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.goodsSortService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!", true);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品分类表-通过id查询")
    @ApiOperation(value = "商品分类表-通过id查询", notes = "商品分类表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GoodsSort goodsSort = goodsSortService.getById(id);
        if (goodsSort == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(goodsSort);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param goodsSort
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GoodsSort goodsSort) {
        return super.exportXls(request, goodsSort, GoodsSort.class, "商品分类表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GoodsSort.class);
    }


    /**
     * 删除状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "删除状态开关更新-通过id更新")
    @ApiOperation(value = "删除状态开关更新-通过id更新", notes = "删除状态开关更新-通过id更新")
    @GetMapping(value = "/delFlagChange/{id}")
    public Result<?> delFlagChange(@PathVariable("id") String id) {

        boolean flag = goodsSortService.removeById(id);
        return Result.OK("删除成功!", flag);
    }

    /**
     * 显示状态开关更新
     *
     * @param id
     * @return
     */
    @AutoLog(value = "显示状态开关更新-通过id更新")
    @ApiOperation(value = "显示状态开关更新-通过id更新", notes = "显示状态开关更新-通过id更新")
    @GetMapping(value = "/isShowChange/{id}")
    public Result<?> isShowChange(@PathVariable("id") String id) {
        GoodsSort goodsSort = goodsSortService.getById(id);
        goodsSort.setIsShow(goodsSort.getIsShow().equals("0") ? "1" : "0");
        goodsSortService.updateById(goodsSort);
        return Result.OK("操作成功", goodsSort);
    }
}
